#include "fileserver.h"

#include "msgsocket.h"
#include "command.h"
#include "databasemagr.h"

FileServer::FileServer(QObject *parent) :
    AbsServer(parent)
{
}

FileServer::~FileServer()
{
    qDebug() << "tcp server close";
    foreach (FileSocket *client, m_clients) {
        m_clients.removeOne(client);
        client->Close();
    }
}

void FileServer::SltNewConnection()
{
    qDebug() << "MsgServer::SltNewConnection()";
    FileSocket *client = new FileSocket(this, m_tcpServer->nextPendingConnection());
    connect(client, SIGNAL(signalConnected()),
            this, SLOT(SltConnected()));
    connect(client, SIGNAL(signalDisConnected()),
            this, SLOT(SltDisConnected()));
}

/**
 * @brief FileServer::SltConnected
 * socket管理
 */
void FileServer::SltConnected()
{
    FileSocket *client = (FileSocket *)this->sender();
    if (NULL == client) return;

    m_clients.push_back(client);
}

/**
 * @brief FileServer::SltDisConnected
 */
void FileServer::SltDisConnected()
{
    FileSocket *client = (FileSocket *)this->sender();
    if (NULL == client) return;

    for (int i = 0; i < m_clients.size(); i++) {
        if (client == m_clients.at(i))
        {
            m_clients.remove(i);
            return;
        }
    }

    disconnect(client, SIGNAL(signalConnected()), this, SLOT(SltConnected()));
    disconnect(client, SIGNAL(signalDisConnected()), this, SLOT(SltDisConnected()));
}

/**
 * @brief FileServer::SltClientDownloadFile
 * 客户端请求下载文件
 */
void FileServer::SltClientDownloadFile(const QJsonValue &json)
{
    // 根据ID寻找连接的socket
    if (json.isObject()) {
        QJsonObject jsonObj = json.toObject();
        qint32 nId = jsonObj.value("from").toInt();
        qint32 nWid = jsonObj.value("id").toInt();;
        QString fileName = jsonObj.value("msg").toString();
        qDebug() << "get file" << jsonObj << m_clients.size();
        for (int i = 0; i < m_clients.size(); i++) {
            if (m_clients.at(i)->CheckUserId(nId, nWid))
            {
                m_clients.at(i)->StartTransferFile(fileName);
                return;
            }
        }
    }
}
